package thread.exercise;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User:22954
 * Date:2024-03-07
 * Time:22:35
 */
public class Exercise4 {
    public static void main(String[] args) {
        BankCard bankCard = new BankCard();
        Thread thread1 = new Thread(bankCard, "user1");
        Thread thread2 = new Thread(bankCard, "user2");
        thread1.start();
        thread2.start();
    }
}

class BankCard implements Runnable {
    static int deposit = 10000;
    private boolean loop = true;

    @Override
    public void run() {
        while (loop) {
            withdraw();
        }
    }

    public void withdraw() {
        synchronized (this) {
            if (deposit > 0) {
                deposit -= 1000;
                System.out.println(Thread.currentThread().getName() + "取走1000元  余额为:" + deposit);
            } else {
                System.out.println("余额不足");
                loop = false;
            }
        }
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
